import React from 'react';

import {
  View,
  Text,
  Image,
  ScrollView,
  TouchableOpacity,
  ListView,
  WebView
} from 'react-native';

import SizeUtils from '../../common/SizeUtils';
import ToastUtils from '../../common/ToastUtils';
import {DateUtils, HtmlUtils} from '../../utils/Utils';
import TImage from '../../components/TImage';
import {Button} from 'react-native-elements';
import Config from '../../config';
import BasePage from '../common/BasePage';
import BaseItem from '../common/BaseItem';
import CommonStyles from '../../common/CommonStyles';
import JifenMallSignAction from '../../actions/jifenmall/JifenMallSignAction';
import JifenMallItemAction from '../../actions/jifenmall/JifenMallItemAction';
import JifenMallPointConfigAction from '../../actions/jifenmall/JifenMallPointConfigAction';
import JifenMallToSignAction from '../../actions/jifenmall/JifenMallToSignAction';
import {getDay,startOfMonth,endOfMonth,format,getDate} from 'date-fns';

const weekTitleArr = ['一','二','三','四','五','六','日'];
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
//sign 协议
export default class JifenQiandaoPage extends BasePage {
  constructor(props) {
    super(props);

    this.state.statusText = "";

    this.weekDayTitle = [{title:"第一天", index:1}, {title:"第二天", index:2}, {title:"第三天", index:3}, {title:"第四天", index:4},{title:"第五天", index:5}, {title:"第六天", index:6}, {title:"第七天", index:7} ];
    this.state.data = {};
    this.state.nowDay = new Date().getDate();

    this._imgBgWidth = SizeUtils.getWindowSize().width;
    this._imgBgHeight = SizeUtils.getWindowSize().width / 750 * 510;
    this._noEmpty = true;

    this._dataKey = "item_id";
  }
  componentDidMount() {
    this._requestData();
  }
  componentWillUpdate(nextProps, nextState) {
    super.componentWillUpdate(nextProps, nextState);
    if(nextState.statusText != "") {
      // this.doRefresh();
      ToastUtils.show(nextState.statusText);
      nextState.statusText = "";
    }
  }

  render() {
    return (
      <View style={{width:SizeUtils.getWindowSize().width,
          backgroundColor:'#fff',
          paddingTop:Config.paddingTop,
          height:SizeUtils.getWindowSize().height}}>
        <ScrollView style={{flex:1}}>
          {this._onRenderHeader()}
        </ScrollView>
        {this._renderNavigationBar()}
      </View>
    )
  }
  _onRenderHeader() {
    console.log(this.state)
    return (
      <View style={{width:SizeUtils.getWindowSize().width,backgroundColor:'#fff'}}>
        {this._renderTopView()}
        <View style={{backgroundColor:'#f5f5f5',height:15}}/>
        {this._renderMonth()}
        <View style={{paddingTop:20,paddingRight:20,paddingLeft:20}}>
          {this.state.point_rule?<WebView
            style={{width:SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(80),
      marginLeft:SizeUtils.translateDesignWidthToCode(0),
      marginRight:SizeUtils.translateDesignWidthToCode(0),
      marginTop:SizeUtils.translateDesignHeightToCode(0),
      height:800}}
            source={HtmlUtils.getHtmlWeb(this.state.point_rule)}
          />:null}
          {/**{this._renderGuizeHeader('签到规则')}
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>签到1天（适用于不连续签到）：积分+1；</Text>
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>连续签到第2天-第5天：每日签到积分+3</Text>
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>连续签到5天：额外获得15积分；</Text>
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>连续签到第6天-第30天：每日签到积分+5，</Text>
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>连续签到10天：额外获得20积分奖励；</Text>
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>连续签到20天：额外获得35积分奖励；</Text>
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>连续签到30天：额外获得50积分奖励；</Text>
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>连续签到第31天及以上：每日签到积分+8；</Text>
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>当连续签到中断后，则回到初始签到状态重新累计连续签到天数。</Text>
          {this._renderGuizeHeader('抽奖规则')}
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>1.抽奖一次消耗3积分。</Text>
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>2.三网话费流量充值24小时内可充值到账。</Text>
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>3.中奖积分可直接充值到您的APP账户中。</Text>
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>4.如充值失败，系统自动退还本次抽奖积分和抽奖次数。</Text>
          {this._renderGuizeHeader('重要提示')}
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>1.话费充值到您实名认证中的电话号码中。</Text>
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>2.根据运营商流量定制不同，抽奖流量以实际入账流量为准。</Text>
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>3.本活动解释权归大庆油田新媒体中心所有。</Text>
          <Text style={[CommonStyles.secondaryText,{lineHeight:25,fontSize:SizeUtils.translateFontSizeToCode(28)}]}>4.本活动所有奖励为大庆油田新媒体中心提供，与苹果官方无关。</Text>**/}
        </View>
      </View>
    )
  }
  _renderTopView(){
    return (
      <View style={{width:SizeUtils.getWindowSize().width,
        height:SizeUtils.translateDesignHeightToCode(124),
        paddingLeft:SizeUtils.translateDesignWidthToCode(30),
        paddingRight:SizeUtils.translateDesignWidthToCode(30),
        flexDirection:'row',alignItems: 'center',
        backgroundColor:'#fff'}}>
        <TImage source={require("../../../resource/images/jifenmall/today_qiandao.png")}
            style={{width:55, height:55}} translatedSize={true}/>
        <View style={{flex:1,marginLeft:10,height:40}}>
          <View style={{flex:1}}>
            <Text style={{fontSize:14}}>已经连续签到<Text style={{color:'#ee3535'}}>{' '+this.getSignDays()+' '}</Text>天</Text>
          </View>
          <View style={{flex:1,flexDirection:'row',alignItems: 'center',justifyContent: 'space-between',}}>
            <Text style={{fontSize:14}}>当月累计<Text style={{color:'#ee3535'}}>{' '+this.getPoints()+' '}</Text>积分</Text>
            <TouchableOpacity style={{
              height: SizeUtils.translateDesignHeightToCode(40),
              }} onPress={()=>{this.gotoPage(Config.pages.jifenmall_luckDraw_page)}}>
                <Text style={{fontSize:SizeUtils.translateFontSizeToCode(28),}}>{'积分抽奖 >>'}</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    )
  }
  _renderButtonView(){
    return(
      <TouchableOpacity style={{
          width:(SizeUtils.getWindowSize.width - SizeUtils.translateDesignWidthToCode(40)),
          backgroundColor:'#ee3535',
          justifyContent: 'center',
          alignItems: 'center',
          borderRadius:4,
          height: SizeUtils.translateDesignHeightToCode(88),
          margin:SizeUtils.translateDesignWidthToCode(30),
        }} onPress={()=>{this.gotoPage(Config.pages.jifenmall_luckDraw_page)}}>
        <Text style={{fontSize:SizeUtils.translateFontSizeToCode(30),color:'#fff'}}>{'积分抽奖'}</Text>
      </TouchableOpacity>
    );
  }
  _getViewStyle() {
    return {paddingTop:0,
        backgroundColor:"#ffffff"}
  }

  _getListViewStyle() {
    return {
        width:SizeUtils.getWindowSize().width,
        height:SizeUtils.getWindowSize().height,
        backgroundColor:"#ffffff00"};
  }

  _requestPoint(){
    new JifenMallSignAction().call(this, {});
    new JifenMallPointConfigAction().call(this, {});
  }

  getSignDays(){
    if(this.state.data && this.state.data.continue_days != undefined)
    {
      return this.state.data.continue_days;
    }
    else {
      return 0;
    }
  }

  getPoints(){
    if(this.state.data && this.state.data.points != undefined)
    {
      return this.state.data.points;
    }
    else {
      return 0;
    }
  }
  _renderGuizeHeader(headerTitle) {
    return (
      <View
        style={{
          flexDirection: "row",
          paddingLeft: SizeUtils.translateDesignWidthToCode(0),
          paddingRight: SizeUtils.translateDesignWidthToCode(0),
          paddingBottom: SizeUtils.translateDesignHeightToCode(20),
          justifyContent: "space-between",
          paddingTop: SizeUtils.translateDesignHeightToCode(30),
          alignItems: "center"
        }}
      >
        <View style={{ flexDirection: "row", alignItems: "center" }}>
          <TImage
            source={require("../../../resource/images/home/biaotitle.png")}
            style={{ width: 8, height: 30 }}
          />
          <Text
            style={{
              fontSize: SizeUtils.translateFontSizeToCode(28),
              color: "#333333",
              marginLeft: SizeUtils.translateDesignWidthToCode(8),
              borderWidth: 0,
              backgroundColor: "#00000000",
            }}
          >
            {headerTitle}
          </Text>
        </View>
      </View>
    );
  }
  getMonthConet(count,arr,widthI,startIdex){
    let list =[];
    const all =count*7;
    const daynumber =getDate(endOfMonth(new Date()));
    for (var i = 0; i < all; i++) {
      if (startIdex-1 < i && i<(startIdex+daynumber) ) {
        const item = arr[i-startIdex];
        const f= this.state.nowDay===(i-startIdex+1)?26:30;
        list.push(
          <View key={i} style={{
            width:widthI,height:widthI,
            borderLeftWidth:i%7===0?1:0,
            borderBottomWidth:1,
            alignItems: 'center',
            justifyContent: 'center',
            borderRightWidth:1,borderColor:'#ccc',
          }}>
            <View style={{width:widthI*0.6,height:widthI*0.6,
              borderRadius:widthI*0.6/2,
              alignItems: 'center',
              backgroundColor:item ==1?'#ee3535':'#0000',
              justifyContent: 'center',}}>
               <Text style={{fontSize:SizeUtils.translateFontSizeToCode(f),
                  backgroundColor:'#ffffff00',
                  color:item ==1?'#fff':"#636363",}}>{(this.state.nowDay===(i-startIdex+1))?'今日':i-startIdex+1}</Text> 
            </View> 
          </View>
        )
      }else{
        list.push(
          <View key={i} style={{
            width:widthI,height:widthI,
            borderBottomWidth:1,borderColor:'#ccc',
            borderRightWidth:1,
            borderLeftWidth:i===0?1:0,
          }} />
        )
      }
    }
    return list;
  }
  _renderMonth(){
    if (!this.state.data.month_signed) {return(<View/>)}
    const arr= this.state.data.month_signed.split(",");
    const  t = getDay(startOfMonth(new Date()));
    const startIdex=Math.max(0,(t===0?7:t)-1);
    const count =Math.ceil((startIdex+arr.length-1)/7);
    const widthAll = SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(40);
    const widthI = Math.floor(widthAll/7);
    return(
      <View style={{
        width:widthI*7+1,
        alignSelf:'center',
        height:widthI*count+SizeUtils.translateDesignHeightToCode(67+90),
        flexDirection:'row',
        marginTop:SizeUtils.translateDesignHeightToCode(15),
        justifyContent: 'center',
        flexWrap:'wrap'
        }}>
        <View style={{height:SizeUtils.translateDesignHeightToCode(90),
          width:widthI*7+1,
          flexDirection:'row',
          alignItems: 'center',
          }}>
          <TImage source={require("../../../resource/images/jifenmall/rili.png")}
            style={{width:20, height:20}} translatedSize={true}/>
            <Text style={{marginLeft:6,fontSize:SizeUtils.translateFontSizeToCode(28),}}>{format(new Date(),'YYYY-MM-DD')}</Text>
        </View>
        <View style={{height:SizeUtils.translateDesignHeightToCode(66),
          width:widthI*7+1,
          flexDirection:'row',
          borderTopWidth:2,borderColor:'#ee3535',
          justifyContent: 'space-around',
          alignItems: 'center',
          backgroundColor:'#fcedea'
          }}>
          {
            weekTitleArr.map((item,index)=>{
              return (<Text key={index} style={{fontSize:SizeUtils.translateFontSizeToCode(24),}}>{item}</Text>);
            })
          }
        </View>
        {this.getMonthConet(count,arr,widthI,startIdex)}
      </View>
    );
  }
  _onToSign(){
    new JifenMallToSignAction().call(this, {});
  }

  _renderDayOfWeek(data, index){
    return(
      <View key={index} style={{flexDirection:"column", alignItems:'center',
        width:SizeUtils.translateDesignWidthToCode(140), height:SizeUtils.translateDesignWidthToCode(150)}}>
        <TImage resizeMode={'contain'} source={require("../../../resource/images/jifenmall/sign_icon_integral.png")}
           style={{width:120, height:150}}  />
        {this._renderSingedShowImage(data)}
        <Text style={{position:"absolute", bottom:SizeUtils.translateDesignWidthToCode(6),
          color:"#fff", fontSize:SizeUtils.translateFontSizeToCode(24)}}>{data.title}</Text>
      </View>
    )
  }

  _renderSingedShowImage(data) {
    if(data.index <= this.state.data.continue_days) {
      return (
        <View style={{width:SizeUtils.translateDesignWidthToCode(140), height:SizeUtils.translateDesignWidthToCode(150),
          flexDirection:"row", alignItems:"center", justifyContent:"center", position:"absolute"}}>
          <TImage resizeMode={'contain'} source={require('../../../resource/images/jifenmall/qiandao_icon_picked.png')}
              style={{width:120, height:150}}/>
        </View>
      )
    }
  }

  _getDayShowText(data) {
    if(data.index <= this.state.data.continue_days) {
      return (
        <Text style={{position:"absolute",
            fontSize:SizeUtils.translateFontSizeToCode(28),
            color:"#cccccc", bottom:SizeUtils.translateDesignHeightToCode(20)}}>
            已领取
        </Text>
      )
    }
    else {
      return (
        <Text style={{position:"absolute",
            fontSize:SizeUtils.translateFontSizeToCode(28),
            color:"#FFC0CB", bottom:SizeUtils.translateDesignHeightToCode(20)}}>
            {this.getWeekDayPoint(data.index)}积分
        </Text>
      )
    }
  }

  _renderSinged(index)
  {
    if(this.state.data && this.state.data.continue_days != undefined)
    {
      //今天未签到
      if(index == this.state.data.continue_days && this.state.data.is_today_signed === 0) {
        return(
          <View style={{position:"absolute",
              width:SizeUtils.translateDesignWidthToCode(160), height:SizeUtils.translateDesignWidthToCode(200),
              borderRadius:SizeUtils.translateDesignNumToCode(20),
              backgroundColor:"#cccccc66"}}>
            <TImage source={require("../../../resource/images/quanzi/quanzi_btn_h.png")}
              resizeMode="contain" style={{width:42, height:41, position:"absolute",
                right:SizeUtils.translateDesignWidthToCode(10), bottom:SizeUtils.translateDesignHeightToCode(10)}}/>
          </View>
        )
      }
    }
  }

  getWeekDayPoint(index){
    if(this.state.data && this.state.data.day_points_rules != undefined)
    {
      if(this.state.data.day_points_rules[index] != undefined)
      {
        return this.state.data.day_points_rules[index];
      }
    }
  }

  _requestData() {
    new JifenMallItemAction().call(this, {sort_id:3, tag:0});
    this._requestPoint();
  }

  _onPressItem(activityData) {

  }

  _onRenderItem(data, index) {
    return (<Item data={data} />);
  }
}

class Item extends BaseItem {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <View style={{borderBottomWidth:SizeUtils.translateDesignHeightToCode(3),
          paddingTop:SizeUtils.translateDesignHeightToCode(20),
          paddingBottom:SizeUtils.translateDesignHeightToCode(30),
          borderColor:"#eeeeee"}}>
        <TouchableOpacity onPress={this._onPressItem.bind(this)}
          style={{flex:1, flexDirection:"column", alignItems:"center",
              paddingLeft:SizeUtils.translateDesignWidthToCode(40),
              paddingRight:SizeUtils.translateDesignWidthToCode(40),}}>
          <TImage source={this._getImageSource(this.props.data)}
             style={{width:SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(80),
               height:(SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(80)) / 330 * 180}}
               translatedSize={true} />
          <View style={{flexDirection:"row", top:SizeUtils.translateDesignHeightToCode(20),
              width:SizeUtils.getWindowSize().width, alignItems:"center"}}>
            <Text numberOfLines={1} style={{left:SizeUtils.translateDesignWidthToCode(80),
              width:SizeUtils.translateDesignWidthToCode(400), fontSize:SizeUtils.translateFontSizeToCode(28)}}>
              {this._getName(this.props.data)}
              <Text style={{color:"#cccccc", fontSize:SizeUtils.translateFontSizeToCode(28)}}>
                {"  " + this._getPrice(this.props.data)}积分
              </Text>
            </Text>
            {this._renderBtn()}
          </View>
        </TouchableOpacity>
      </View>
    )
  }

  _getName(data){
    var str = "";
    if(data.name)
    {
      str = data.name;
    }
    return str;
  }

  _getPrice(data){
    var num = 0;
    if(data.price != undefined){
      num = data.price;
    }
    return num;
  }

  _renderBtn(){
    return(
      <View
        style={{alignItems:"center", backgroundColor: '#ffffff', borderColor:"#cccccc",
        borderWidth:SizeUtils.translateDesignNumToCode(3), borderRadius:SizeUtils.translateDesignNumToCode(10),
        width:SizeUtils.translateDesignWidthToCode(150),justifyContent:"center",
        height: SizeUtils.translateDesignHeightToCode(60), left:SizeUtils.translateDesignWidthToCode(160)}}
      >
        <Text
          style={{color:'#000000', fontSize:SizeUtils.translateFontSizeToCode(26), }}
        >兑换</Text>
      </View>
    )
  }

  _onPressItem() {
    this.gotoPage(Config.pages.jifenmall_duihuan_item_content, {itemData:this.props.data});
  }

  _getImageSource(data) {
    if(data.image_url) {
      return {uri: data.image_url};
    }
    else {
      return {uri: ""};
    }
  }
}
